﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
using System.IO;
using BarCode.AccessDao;
using BarCode.Module;
using BarCode.Common;
using BarCode.Bean;

namespace BarCode.Forms
{
    public partial class GasMain : Form
    {
        private static readonly log4net.ILog LogUtil = log4net.LogManager.GetLogger(typeof(GasMain));

        private SerialPort ComDevice = new SerialPort();
        private string btCode = "";
        private string bhCode = "";

        private int clearTime = 3;


        private string currentMdbFile;
        
        private int BaudRate = 9600; // 波特率
        private bool bodyNoFlag = false; // 是否显示表体

        private int waitSeconds = 1; // 指令发送间隔时间(单位：秒) 

        private int workAmount;

        public GasMain()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {

            // 读取是否显示表体
            string bodyNoDis = IniFileHelper.ReadValue("System", "BodyNo_Display");
            if ("1".Equals(bodyNoDis))
            {
                bodyNoFlag = true;
            }
            else
            {
                lblBT.Visible = false;
                txtBT.Visible = false;
                lblBH.Location = new Point(113, 280);
                txtBH.Location = new Point(188, 278);
            }

            // 获取波特率
            string strBaudRate = IniFileHelper.ReadValue("System", "BaudRate");
            try
            {
                BaudRate = Convert.ToInt32(strBaudRate);
            }
            catch (Exception ex)
            {
                LogUtil.Error("波特率获取失败", ex);
            }
            lblBaudRate.Text = BaudRate.ToString();

            // 读取厂商标识
            txtMID.Text = IniFileHelper.ReadValue("System", "MID");
            txtPID.Text = IniFileHelper.ReadValue("System", "PID");

            // 读取CSV信息
            GlobalVal.csvFilePath = IniFileHelper.ReadValue("System", "CSV_DIR");
            GlobalVal.csvFileName = IniFileHelper.ReadValue("System", "FILE_NAME");

            // 清屏时间
            string strClearTime = IniFileHelper.ReadValue("System", "CLEAR_TIME");
            try
            {
                clearTime = Convert.ToInt32(strClearTime);
            }
            catch (Exception ex) {
                LogUtil.Error("清屏时间获取失败", ex);
                clearTime = 3;
            }
            LogUtil.Info("清屏时间：" + clearTime);

            // 指令发送间隔时间
            string strWaitSeconds = IniFileHelper.ReadValue("System", "WaitSeconds");
            try
            {
                waitSeconds = Convert.ToInt32(strWaitSeconds);
                if (waitSeconds < 0)
                {
                    waitSeconds = 0;
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error("指令发送间隔时间获取失败", ex);
                waitSeconds = 1;
            }
            LogUtil.Info("指令发送间隔时间(秒)：" + waitSeconds);

            // 加载端口
            LoadPorts();
            //ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件
            // 获取默认端口配置
            string defaultCom = IniFileHelper.ReadValue("System", "DEFAULT_COM");
            if (!string.IsNullOrEmpty(defaultCom))
            {
                cbbComList.SelectedItem = defaultCom;
            }

            txtBT.Text = "";
            txtBH.Text = "";
            btnOpen.Focus();
            lblStatus.Text = "";
            cmbNetwork.SelectedIndex = 0;
            cmbDirection.SelectedIndex = 0;

            // 获取当前用户当天的工作量
            DB01Dao db01 = new DB01Dao(GlobalVal.serverMysqlInfo.MYSQL_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
            workAmount = db01.getGasWorkAmount(GlobalVal.CurrentUser.User);
            lblAmount.Text = (workAmount + GlobalVal.BASE_COUNT).ToString();

        }

        private void LoadPorts()
        {
            cbbComList.Items.AddRange(SerialPort.GetPortNames());
            if (cbbComList.Items.Count > 0)
            {
                cbbComList.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 重新打开串口
        /// </summary>
        private void ReloadPorts()
        {
            LogUtil.Info("重启串口-----");
            if (cbbComList.Items.Count <= 0)
            {
                MessageBox.Show("没有发现串口,请检查线路！");
                return;
            }

            // 关闭串口
            try
            {
                ComDevice.Close();
            }
            catch (Exception ex)
            {
                lblStatus.Text = "重新打开串口异常";
                LogUtil.Error("串口关闭异常", ex);
            }

            ComDevice.PortName = cbbComList.SelectedItem.ToString();
            ComDevice.BaudRate = BaudRate;
            ComDevice.Parity = Parity.None;
            ComDevice.DataBits = 8;
            ComDevice.StopBits = StopBits.One;
            try
            {
                ComDevice.Open();

            }
            catch (Exception ex)
            {
                lblStatus.Text = ex.Message;
                LogUtil.Error("串口打开异常", ex);
                return;
            }
            btnOpen.Text = "关闭串口";
            //lblStatus.Text = "串口重新加载正常，可以开始工作";
            txtBT.Focus();
            pictureBox1.BackgroundImage = Properties.Resources.green;

            cbbComList.Enabled = !ComDevice.IsOpen;
        }

        ///// <summary>
        ///// 接收数据
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
        //{
        //    byte[] ReDatas = new byte[ComDevice.BytesToRead];
        //    ComDevice.Read(ReDatas, 0, ReDatas.Length);//读取数据
        //    logReceiveData(ReDatas);//输出数据
        //}

        private void txtBT_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (char)13)
            {
                return;
            }
            //if (ComDevice.IsOpen == false)
            //{
            //    lblStatus.Text = "请先打开串口！";
            //    return;
            //}

            btCode = txtBT.Text;
            if (String.IsNullOrEmpty(btCode))
            {
                lblStatus.Text = "表体不能为空！";
                txtBT.Focus();
                return;
            }

            if (!btCode.StartsWith("7") || btCode.Length != 12)
            {
                lblStatus.Text = "表体必须是以7开头的12位号码！";
                txtBT.Focus();
                return;
            }

            lblStatus.Text = "请扫描表号";
            txtBH.Focus();

        }

        private void txtBH_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != (char)13)
            {
                return;
            }
            lblStatus.ForeColor = Color.Blue;
            ReloadPorts();
            //if (ComDevice.IsOpen == false)
            //{
            //    lblStatus.Text = "请先打开串口！";
            //    return;
            //}

            // 检查MID厂商标识
            if (String.IsNullOrEmpty(txtMID.Text))
            {
                errorMsg("MID厂商标识不能为空！");
                txtMID.Focus();
                ComUtil.sendFail(workAmount);
                return;
            }

            if (txtMID.Text.Length != 6)
            {
                errorMsg("MID厂商标识必须是6位号码！");
                txtMID.Focus();
                ComUtil.sendFail(workAmount);
                return;
            }

            // 检查PID产品标识
            if (String.IsNullOrEmpty(txtPID.Text))
            {
                errorMsg("PID产品标识不能为空！");
                txtPID.Focus();
                ComUtil.sendFail(workAmount);
                return;
            }

            if (txtPID.Text.Length != 6)
            {
                errorMsg("PID产品标识必须是6位！");
                txtPID.Focus();
                ComUtil.sendFail(workAmount);
                return;
            }

            // 检查表体
            if (bodyNoFlag)
            {
                btCode = txtBT.Text;
                if (String.IsNullOrEmpty(btCode))
                {
                    errorMsg("表体不能为空！");
                    txtBT.Focus();
                    ComUtil.sendFail(workAmount);
                    return;
                }
                if (!btCode.StartsWith("7") || btCode.Length != 12)
                {
                    errorMsg("表体必须是以7开头的12位号码！");
                    txtBT.Focus();
                    ComUtil.sendFail(workAmount);
                    return;
                }
            }

            bhCode = txtBH.Text;
            // 检查表号
            if (String.IsNullOrEmpty(bhCode))
            {
                errorMsg("表号不能为空！");
                txtBH.Focus();
                ComUtil.sendFail(workAmount);
                return;
            }

            if (bhCode.Length != 12)
            {
                errorMsg("表号必须是12位号码！");
                txtBH.Focus();
                ComUtil.sendFail(workAmount);
                return;
            }

            this.Cursor = Cursors.WaitCursor;
            string receiveStr = "";

            try
            {
                // 查询前道工序是否存在
                DB01Dao db01 = new DB01Dao(GlobalVal.serverMysqlInfo.MYSQL_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                string preUser = db01.getPreUser(btCode);
                if (string.IsNullOrEmpty(preUser))
                {
                    lblStatus.ForeColor = Color.Red;
                    lblStatus.Text = "主控板安装记录不存在";
                    ComUtil.sendFail(workAmount);
                    return;
                }

                //// 2) 读取IMEI并按照规则转换成ASKII码发送给主板
                //string getIMEICode = createSearchIMEI();
                //lblStatus.Text = "IMEI号查询处理中 ... ";
                //Application.DoEvents();
                //receiveStr = sendData(getIMEICode);
                //if (String.IsNullOrEmpty(receiveStr))
                //{
                //    lblStatus.Text = "IMEI号查询失败，请重试";
                //    this.Cursor = Cursors.Default;
                //    return;
                //}
                //else if (!receiveStr.StartsWith("68 84"))
                //{
                //    lblStatus.Text = "接收数据不正确，请重试";
                //    receiveUseless();
                //    this.Cursor = Cursors.Default;
                //    return;
                //}
                //string imieCode = receiveStr.Substring(receiveStr.IndexOf("68 84 0F ") + "68 84 0F ".Length);
                //imieCode = imieCode.Substring(0, imieCode.Length - 6);
                //imieCode = HexStringToASCII(imieCode);
                //LogUtil.Info("查询获取IMEI号：" + imieCode);

                //// 0927 微信说明 增加ICCID查询
                //showWaitStatus("({0:D})秒后发送ICCID查询指令 ... ", 4);
                //// 2) 读取ICCID
                //string getICCIDCode = createSearchICCID();
                //lblStatus.Text = "ICCID号查询处理中 ... ";
                //Application.DoEvents();
                //receiveStr = sendData(getICCIDCode);
                //if (String.IsNullOrEmpty(receiveStr))
                //{
                //    lblStatus.Text = "ICCID号查询失败，请重试";
                //    this.Cursor = Cursors.Default;
                //    return;
                //}
                //else if (!receiveStr.StartsWith("68 85"))
                //{
                //    lblStatus.Text = "接收数据不正确，请重试";
                //    receiveUseless();
                //    this.Cursor = Cursors.Default;
                //    return;
                //}
                //string ICCIDCode = receiveStr.Substring(receiveStr.IndexOf("68 85 14 ") + "68 85 14 ".Length);
                //ICCIDCode = ICCIDCode.Substring(0, ICCIDCode.Length - 6);
                //ICCIDCode = HexStringToASCII(ICCIDCode);
                //LogUtil.Info("查询获取ICCID号：" + ICCIDCode);

                // 1020微信 查询IMIE和ICCID的指令变更
                string getCode = createSearchIMEI_ICCID();
                lblStatus.Text = "查询IMEI和ICCID处理中 ... ";
                Application.DoEvents();
                receiveStr = sendData(getCode);
                if (String.IsNullOrEmpty(receiveStr))
                {
                    errorMsg("查询IMEI和ICCID失败，请重试", true);
                    this.Cursor = Cursors.Default;
                    ComUtil.sendFail(workAmount);
                    return;
                }
                else if (!receiveStr.StartsWith("68 84"))
                {
                    errorMsg("查询IMEI和ICCID失败，请重试", true);
                    receiveUseless();
                    this.Cursor = Cursors.Default;
                    ComUtil.sendFail(workAmount);
                    return;
                }
                string retCode = receiveStr.Substring(receiveStr.IndexOf("68 84 23 ") + "68 84 23 ".Length);
                retCode = retCode.Substring(0, retCode.Length - 6);
                retCode = HexStringToASCII(retCode);
                retCode = retCode.Replace("\0", " ");
                LogUtil.Info("查询获取解析结果码:" + retCode);
                string imeiCode = retCode.Substring(0, 15);
                LogUtil.Info("查询获取IMEI号：" + imeiCode);
                if (String.IsNullOrEmpty(imeiCode.Trim()))
                {
                    errorMsg("未查询到IMEI号码，请重试", true);
                    this.Cursor = Cursors.Default;
                    ComUtil.sendFail(workAmount);
                    return;
                }

                string iccidCode = "";
                if (retCode.Length > 15)
                {
                    iccidCode = retCode.Substring(15, 20);
                    LogUtil.Info("查询获取ICCID号：" + iccidCode);
                }
                else
                {
                    errorMsg("未查询到ICCDI号码，请重试", true);
                    this.Cursor = Cursors.Default;
                    ComUtil.sendFail(workAmount);
                    return;
                }
                //iccidCode = "89860438151840130039"; // TODO 测试用

                // 2021.05.31 邹总微信指示 调整顺序
                if (waitSeconds > 0)
                {
                    showWaitStatus("({0:D})秒后发送DID码指令 ... ", waitSeconds);
                }
                // 1) 将表号生成DID码并按照规则转换成ASCII码发送给主板
                string bhSendCode = createDIDSendCode();
                lblStatus.Text = "DID码发送处理中 ... ";
                receiveStr = sendData(bhSendCode);
                if (String.IsNullOrEmpty(receiveStr))
                {
                    errorMsg("DID码发送失败，请重试");
                    this.Cursor = Cursors.Default;
                    ComUtil.sendFail(workAmount);
                    return;
                }
                else if (!receiveStr.StartsWith("68 8A"))
                {
                    errorMsg("接收数据不正确，请重试");
                    receiveUseless();
                    this.Cursor = Cursors.Default;
                    ComUtil.sendFail(workAmount);
                    return;
                }



                // 0923 微信说明 去除发送IMEI
                //string imeiSendCode = createIMEISendCode(imieCode);
                //lblStatus.Text = "IMEI号发送处理中 ... ";
                //Application.DoEvents();
                //Thread.Sleep(2000);
                //receiveStr = sendData(imeiSendCode);
                //if (String.IsNullOrEmpty(receiveStr))
                //{
                //    lblStatus.Text = "IMEI号发送失败，请重试";
                //    return;
                //}

                // 保存数据库
                GasCodeInfo info = new GasCodeInfo();
                info.body_no = btCode;
                info.meters_no = bhCode;
                info.did_code = txtMID.Text + txtPID.Text + bhCode;
                info.imei_code = imeiCode;
                info.iccid_code = iccidCode;
                info.Opt_date = DateTime.Now;
                info.network_operator = cmbNetwork.Text;
                info.operator_name = GlobalVal.CurrentUser.User;
                info.meter_direction = cmbDirection.Text;
                logSaveInfo(info);
                int ret = saveMysqlInfo(info);
                if (ret == 1)
                {
                    lblStatus.Text = "保存成功, 请扫描下一个";
                    txtBT.Text = "";
                    txtBH.Text = "";
                    txtBT.Focus();

                    // 工作量
                    workAmount = db01.getGasWorkAmount(GlobalVal.CurrentUser.User);
                    lblAmount.Text = (workAmount + GlobalVal.BASE_COUNT).ToString();

                    ComUtil.sendSuccess(workAmount);
                }
                else
                {
                    errorMsg("保存失败，请联系管理员");
                    ComUtil.sendFail(workAmount);
                }
                this.Cursor = Cursors.Default;

                // 写入CSV
                FileHelper.WriteResultFile(info);

            }
            catch (Exception ex)
            {
                errorMsg("系统异常，请联系管理员查看日志");
                ComUtil.sendFail(workAmount);
            }

        }

        private int saveMysqlInfo(GasCodeInfo info)
        {
            DB01Dao db01 = new DB01Dao(GlobalVal.serverMysqlInfo.MYSQL_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
            return db01.saveGasCode(info);
        }


        private string sendData(string sendCode)
        {
            LogUtil.Info("发送源数据：" + sendCode);
            byte[] sendData = strToHexByte(sendCode);

            if (this.SendData(sendData))
            {
                //读取返回数据
                int waitMillSeconds = 1;
                while (ComDevice.BytesToRead == 0 && waitMillSeconds < 4000)
                {
                    Thread.Sleep(1);
                    Application.DoEvents();
                    waitMillSeconds++;
                }
                Thread.Sleep(100); //100毫秒内数据接收完毕，可根据实际情况调整
                byte[] recData = new byte[ComDevice.BytesToRead];
                ComDevice.Read(recData, 0, recData.Length);
                return logReceiveData(recData);//输出数据
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="data"></param>
        public bool SendData(byte[] data)
        {
            if (ComDevice.IsOpen)
            {
                try
                {
                    ComDevice.Write(data, 0, data.Length);//发送数据
                    return true;
                }
                catch (Exception ex)
                {
                    lblStatus.Text = ex.Message;
                    LogUtil.Error("发送异常", ex);
                }
            }
            else
            {
                lblStatus.Text = "串口未打开";
                LogUtil.Error("串口未打开");
            }
            return false;
        }


        private string receiveUseless()
        {
            LogUtil.Info("尝试接收无用数据  ↓");
            Application.DoEvents();
            try
            {
                //读取返回数据
                int waitMillSeconds = 1;
                while (ComDevice.BytesToRead == 0 && waitMillSeconds < 2000)
                {
                    Thread.Sleep(1);
                    waitMillSeconds++;
                    Application.DoEvents();
                }
                Thread.Sleep(100); //100毫秒内数据接收完毕，可根据实际情况调整
                byte[] recData = new byte[ComDevice.BytesToRead];
                ComDevice.Read(recData, 0, recData.Length);
                return logReceiveData(recData);//输出数据
            }
            finally
            {
                LogUtil.Info("尝试接收无用数据  ↑");
            }

        }

        /// <summary>
        /// 生成发送给主板的DID的编码
        /// </summary>
        private string createDIDSendCode()
        {
            string headStr1 = "FEFEFE";
            string headStr2 = "680A0C";
            string endStr = "16";
            string DIDCode = txtMID.Text + txtPID.Text + txtBH.Text;

            // 校验和计算
            string verifyCode = getVerifyCode(headStr2 + DIDCode);

            // 
            string sendCode = headStr1 + headStr2 + DIDCode + verifyCode + endStr;
            return sendCode;
        }

        /// <summary>
        /// 生成发查询IMEI的发送指令
        /// </summary>
        private string createSearchIMEI()
        {
            string headStr1 = "FEFEFE";
            string headStr2 = "680400";
            string endStr = "16";
            string verifyCode = getVerifyCode(headStr2 + "");
            string sendCode = headStr1 + headStr2 + "" + verifyCode + endStr;
            return sendCode;
        }

        /// <summary>
        /// 生成发查询ICCID的发送指令
        /// </summary>
        private string createSearchICCID()
        {
            string headStr1 = "FEFEFE";
            string headStr2 = "680500";
            string endStr = "16";
            string verifyCode = getVerifyCode(headStr2 + "");
            string sendCode = headStr1 + headStr2 + "" + verifyCode + endStr;
            return sendCode;
        }

        /// <summary>
        /// 生成发查询IMEI&ICCID的发送指令
        /// </summary>
        private string createSearchIMEI_ICCID()
        {
            string headStr1 = "FEFEFE";
            string headStr2 = "680400";
            string endStr = "16";
            string verifyCode = getVerifyCode(headStr2 + "");
            string sendCode = headStr1 + headStr2 + "" + verifyCode + endStr;
            return sendCode;
        }

        /// <summary>
        /// 生成IMIE发送Code
        /// </summary>
        /// <param name="imieCode"></param>
        /// <returns></returns>
        private string createIMEISendCode(string imieCode)
        {
            string headStr1 = "FEFEFE";
            string headStr2 = "680E0F";
            string endStr = "16";

            StringBuilder codeContent = new StringBuilder("");
            for (int i = 0; i < imieCode.Length; i++)
            {
                codeContent.Append("3");
                codeContent.Append(imieCode.Substring(i, 1));
            }
            // 校验和
            string verifyCode = getVerifyCode(headStr2 + codeContent.ToString());
            return headStr1 + headStr2 + codeContent.ToString() + verifyCode + endStr;

        }


        private string getVerifyCode(string verifySourceStr)
        {

            int verifyResult = 0;
            for (int i = 0; i < verifySourceStr.Length / 2; i++)
            {
                verifyResult += Convert.ToInt32(verifySourceStr.Substring(i * 2, 2), 16);

            }
            string verifyCode = Convert.ToString(verifyResult, 16).ToUpper();
            verifyCode = verifyCode.Substring(verifyCode.Length - 2);
            return verifyCode;
        }


        /// <summary>
        /// 将一条十六进制字符串转换为ASCII
        /// </summary>
        /// <param name="hexstring">一条十六进制字符串</param>
        /// <returns>返回一条ASCII码</returns>
        private string HexStringToASCII(string hexstring)
        {
            byte[] bt = HexStringToBinary(hexstring);
            string lin = "";
            for (int i = 0; i < bt.Length; i++)
            {
                lin = lin + bt[i] + " ";
            }


            string[] ss = lin.Trim().Split(new char[] { ' ' });
            char[] c = new char[ss.Length];
            int a;
            for (int i = 0; i < c.Length; i++)
            {
                a = Convert.ToInt32(ss[i]);
                c[i] = Convert.ToChar(a);
            }

            string b = new string(c);
            return b;
        }

        /**/
        /// <summary>
        /// 16进制字符串转换为二进制数组
        /// </summary>
        /// <param name="hexstring">用空格切割字符串</param>
        /// <returns>返回一个二进制字符串</returns>
        private byte[] HexStringToBinary(string hexstring)
        {

            string[] tmpary = hexstring.Trim().Split(' ');
            byte[] buff = new byte[tmpary.Length];
            for (int i = 0; i < buff.Length; i++)
            {
                buff[i] = Convert.ToByte(tmpary[i], 16);
            }
            return buff;
        }

        /// <summary>
        /// 输出串口接收信息
        /// </summary>
        /// <param name="data"></param>
        private string logReceiveData(byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sb.AppendFormat("{0:x2}" + " ", data[i]);
            }
            LogUtil.Info("串口接收信息：" + sb.ToString().ToUpper());
            return sb.ToString().ToUpper();
        }

        /// <summary>
        /// 字符串转换16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        private byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0) hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);
            return returnBytes;
        }

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (cbbComList.Items.Count <= 0)
            {
                MessageBox.Show("没有发现串口,请检查线路！");
                return;
            }

            if (ComDevice.IsOpen == false)
            {
                ComDevice.PortName = cbbComList.SelectedItem.ToString();
                ComDevice.BaudRate = BaudRate;
                ComDevice.Parity = Parity.None;
                ComDevice.DataBits = 8;
                ComDevice.StopBits = StopBits.One;
                try
                {
                    ComDevice.Open();

                }
                catch (Exception ex)
                {
                    lblStatus.Text = ex.Message;
                    LogUtil.Error("串口打开异常", ex);
                    return;
                }
                btnOpen.Text = "关闭串口";
                lblStatus.Text = "串口打开正常，可以开始工作";
                txtBT.Focus();
                pictureBox1.BackgroundImage = Properties.Resources.green;
            }
            else
            {
                try
                {
                    ComDevice.Close();
                }
                catch (Exception ex)
                {
                    lblStatus.Text = ex.Message;
                    LogUtil.Error("串口关闭异常", ex);
                }
                btnOpen.Text = "打开串口";
                lblStatus.Text = "请先打开串口";
                pictureBox1.BackgroundImage = Properties.Resources.red;
            }
            cbbComList.Enabled = !ComDevice.IsOpen;
        }

        private void logSaveInfo(GasCodeInfo info)
        {
            StringBuilder logInfo = new StringBuilder();
            logInfo.Append("保存数据：");
            logInfo.Append("\t");
            logInfo.Append(info.body_no);
            logInfo.Append("\t");
            logInfo.Append(info.meters_no);
            logInfo.Append("\t");
            logInfo.Append(info.did_code);
            logInfo.Append("\t");
            logInfo.Append(info.imei_code);
            logInfo.Append("\t");
            logInfo.Append(info.iccid_code);
            logInfo.Append("\t");
            logInfo.Append(info.Opt_date.ToString("yyyyMMdd HH:mm:ss"));
            logInfo.Append("\t");
            logInfo.Append(info.network_operator);
            logInfo.Append("\t");
            logInfo.Append(info.meter_direction);
            logInfo.Append("\t");
            logInfo.Append(info.operator_name);
            LogUtil.Debug(logInfo.ToString());
        }

        private void showWaitStatus(string statusInfo, int seconds)
        {
            for (int i = seconds; i > 0; i--)
            {
                Application.DoEvents();
                lblStatus.Text = string.Format(statusInfo, i);
                Thread.Sleep(1000);
            }
        }

        private void errorMsg(string msg, bool clearFlag = false)
        {
            lblStatus.Text = msg;
            lblStatus.ForeColor = Color.Red;
            LogUtil.Error(msg);
            if (clearFlag)
            {
                clearTimer.Interval = clearTime * 1000;
                clearTimer.Enabled = true;
                clearTimer.Start();
            }
        }

        private void infoMsg(string msg)
        {
            lblStatus.Text = msg;
            lblStatus.ForeColor = Color.Blue;
        }

        private void clearTimer_Tick(object sender, EventArgs e)
        {
            txtBT.Text = "";
            txtBH.Text = "";
            lblStatus.Text = "";
            lblStatus.ForeColor = Color.Blue;
            txtBT.Focus();
            clearTimer.Stop();
            clearTimer.Enabled = false;

        }

        private void btnSaveTest_Click(object sender, EventArgs e)
        {
            // 保存数据库
            GasCodeInfo info = new GasCodeInfo();
            info.body_no = txtBT.Text;
            info.meters_no = txtBH.Text;
            info.did_code = txtMID.Text + txtPID.Text + txtBH.Text;
            info.imei_code = "imei_code_test";
            info.iccid_code = "iccid_code_test";
            info.Opt_date = DateTime.Now;
            info.network_operator = cmbNetwork.Text;
            info.operator_name = GlobalVal.CurrentUser.User;
            info.meter_direction = cmbDirection.Text;
            logSaveInfo(info);


            // 查询前道工序是否存在
            DB01Dao db01 = new DB01Dao(GlobalVal.serverMysqlInfo.MYSQL_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
            string preUser = db01.getPreUser(txtBT.Text);
            if (string.IsNullOrEmpty(preUser))
            {
                lblStatus.ForeColor = Color.Red;
                lblStatus.Text = "主控板安装记录不存在";
                ComUtil.sendFail(workAmount);
                return;
            }

            int ret = saveMysqlInfo(info);
            if (ret == 1)
            {
                lblStatus.Text = "保存成功, 请扫描下一个";
                txtBT.Text = "";
                txtBH.Text = "";
                txtBT.Focus();

                workAmount = db01.getGasWorkAmount(GlobalVal.CurrentUser.User);
                lblAmount.Text = (workAmount + GlobalVal.BASE_COUNT).ToString();
                ComUtil.sendSuccess(workAmount);
            }
            else
            {
                errorMsg("保存失败，请联系管理员");
            }

            // 写入CSV
            FileHelper.WriteResultFile(info);
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            //Application.Exit();
        }
    }
}
